<template>
  <div v-if="allowSwitch" class="language">
    <div @click="Open" class="languageSelect">
      <span class="iconfont icon-earth icon"></span>
    </div>
    <base-modal :title="title" :show.sync="isShow" width="550px" :maskCloseable="true" :cancel="Close" :append-to-body="true">
      <div :key="DateKey" class="lang_setting">
        <div class="mb20 color-gray">
          {{ $t('common.languages.settingTips') }}
        </div>
        <div class="form-box">
          <el-form style="display: flex; flex-wrap: wrap; padding: 0 18px" ref="form" :model="form" :rules="rules" :inline="true" label-position="left" label-width="100px" label-suffix="">
            <template v-for="(item, index) in language">
              <transition v-if="!item.isSplit" name="el-zoom-in-top" :key="item.languageKey">
                <el-form-item v-show="!item.isHide" class="w-100P" style="display: flex" :label="item.remark" :prop="item.languageKey">
                  <!-- <template slot="label">{{ item.languageValue }}</template> -->
                  <div class="lang_setting_form">
                    <!-- 单行文本 -->
                    <!-- 中文限制字符数量，其他语言不限制。maxlength 默认最大字符为 524288 -->
                    <template v-if="Option.formType === 'text'">
                      <el-input v-model="form[item.languageKey]" :disabled="Option.disabled" :maxlength="item.languageKey !== 'zh' ? 524288 : Option.maxlength" :placeholder="item.placeholder" />
                    </template>
                    <!-- 多行文本 -->
                    <template v-if="Option.formType === 'textarea'">
                      <el-input type="textarea" v-model="form[item.languageKey]" :disabled="Option.disabled" :maxlength="item.languageKey !== 'zh' ? 524288 : Option.maxlength" :placeholder="item.placeholder" />
                    </template>
                  </div>
                </el-form-item>
              </transition>
              <el-divider v-else :key="index">
                <div class="flex-x">
                  <span class="color-gray">{{ $t('common.languages.expand') }}</span>
                  <el-tooltip class="item" effect="dark" :content="$t('common.languages.expandTips')" placement="top">
                    <i class="iconfont icon-question cur-point ml10 color-gray task-font14" />
                  </el-tooltip>
                </div>
              </el-divider>
            </template>
          </el-form>
        </div>
        <div v-if="showCollege" class="division-box" @click="changeDivisionType">
          {{ divisionType ? $t('common.base.collapse') : $t('common.base.expand') }}
          <div class="transition-box" :class="divisionType ? 'isDivision' : ''">
            <i class="iconfont icon-more" />
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="Close">{{ $t('common.base.cancel') }}</el-button>
        <el-button type="primary" @click="Save">{{ $t('common.base.confirm') }}</el-button>
      </span>
    </base-modal>
  </div>
</template>

<script>
import { DefaultLang, languages, GetCommonDefaultLang, GetTransformI18n, SystemLibrary } from '@src/util/languages.js';
import locales, { t, transformI18n } from '@src/locales';
import { splitLanguages } from 'pub-bbx-global/lang/dist/utils';
import { allowSwitchLanguage } from '@src/util/version';
import { cloneDeep } from 'lodash';
export default {
  name: 'base-select-language',
  data() {
    return {
      isShow: false,
      form: { ...DefaultLang() },
      language: null,
      // 输入框配置初始值
      Option: {
        disabled: false,
        formType: 'text',
      },
      DateKey: Date.now(),
      showCollege: false,
      divisionType: false,
    };
  },
  props: {
    // 标题
    title: {
      type: String,
      default: t('common.base.languageSetting'),
    },
    // 字数限制
    maxlength: {
      type: Number,
      default: 500,
    },
    // 额外校验规则
    AdditionalRules: {
      type: Object,
      default: () => ({}),
    },
    /**
     * 配置输入框参数
     * @params disabled 可填写
     * @params formType 输入框类型
     * @params maxlength 字数限制，优先级高
     */
    defaultOption: {
      type: Object,
      default: () => ({}),
    },
    // 默认参数，参数
    defaultValue: {
      type: String,
      default: '',
    },
    // 默认参数,多语言
    defaultValueLanguage: {
      type: Object,
      default: null,
    },
    field: {
      type: Object,
      default: null,
    },
    // 指定语言库数据
    defaultFormType: {
      type: String,
      default: '',
    },
    isRequire: {
      type: Boolean,
      default: true,
    },
    // 自助门户独有
    selectKey: [String, Number],
    // 是否回填输入框内的数据(门户配置显示中文)
    isFill: {
      type: Boolean,
      default: true,
    },
  },
  mounted() {},
  methods: {
    Save() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.Close();
          this.$emit('save', cloneDeep(this.form), this.selectKey);
        }
      });
    },
    GetLanguage() {
      // 处理TOB TOC语言分割
      const { bArr, cArr } = splitLanguages(languages);
      if (cArr.length > 2) {
        this.showCollege = true;
        this.divisionType = false;
        for (let i = 0; i < cArr.length; i++) {
          if (i > 1) cArr[i].isHide = true;
        }
      }

      this.language = [...bArr, ...(cArr.length ? [{ isSplit: true }] : []), ...cArr];

      for (let i = 0; i < languages.length; i++) {
        // 输入框，默认参数。在语言库中设置
        languages[i].placeholder = transformI18n('common.placeholder.input2', languages[i].languageKey);
      }
    },
    async initData() {
      // 获取初始参数，每次开启重置
      if (this.defaultValueLanguage) {
        // 已有设置的参数，回填
        for (let key in this.defaultValueLanguage) {
          this.$set(this.form, key, this.defaultValueLanguage[key]);
        }
        // 回填当前输入框中的数据，同步数据
        this.isFill && (this.form[locales.locale] = this.defaultValue);
      } else {
        // 没有设置参数，去默认语言库获取参数
        // 语言库数据，优先选择 defaultFormType ，之后根据 组建类型 查找语言库
        let route = SystemLibrary.includes(this.field.fieldName) ? `fieldName.${this.field.fieldName}` : `formType.${this.field?.formType || this.defaultFormType}`;
        this.form = GetCommonDefaultLang({
          formType: route,
          lastValue: this.defaultValue,
        });
        // 回填初始化翻译数据
      }
      this.DateKey = Date.now();
    },
    Open() {
      this.GetLanguage();
      this.isShow = true;
      this.initData();
      this.$nextTick(() => {
        // 重置表单校验
        this.$refs.form.resetFields();
      });
    },
    // 获取 formType 与 language 指定语言库的实参
    GetTransform(formType, language) {
      return GetTransformI18n({
        formType: formType,
        language: language,
      });
    },
    Close() {
      this.isShow = false;
    },
    changeDivisionType() {
      this.language.map(item => {
        if (Reflect.has(item, 'isHide')) {
          item.isHide = this.divisionType;
        }
        return item;
      });
      this.divisionType = !this.divisionType;
    },
  },
  computed: {
    //  表单校验规则
    rules() {
      let rule = {};

      if (this.language?.length) {
        for (let item of this.language) {
          if (item.isSplit) continue;
          rule[item.languageKey] = [];
          // 该字段为必填且主语言必填
          if (item.isMainLanguage && this.isRequire) {
            rule[item.languageKey].push({
              required: true,
              message: this.$t('common.base.moduleIsNotNull', {
                module: item.remark,
              }),
              trigger: 'blur',
            });
          }
        }
      }

      // 额外校验规则
      rule = Object.assign(rule, this.AdditionalRules);

      return rule;
    },
    // 是否允许切换语言包 老版本不限制，新版本只有国际化账号才允许切换语言包
    allowSwitch() {
      return allowSwitchLanguage();
    },
  },
  watch: {
    // 处理默认值
    defaultOption: {
      deep: true,
      immediate: true,
      handler(newValue) {
        // 文本长度初始值
        this.Option.maxlength = this.maxlength;

        if (newValue) {
          for (let key in newValue) {
            this.Option[key] = newValue[key];
          }
        }
      },
    },
  },
};
</script>

<style lang="scss" scoped>
.w-100P {
  width: 100%;
}

.color-gray {
  color: $text-color-secondary;
}

.form-box {
  max-height: 400px;
  overflow-y: auto;
}
.division-box {
  width: 100%;
  height: 24px;
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  color: #595959;
  justify-content: center;
  cursor: pointer;
  .iconfont {
    margin-left: 10px;
    font-size: 10px;
  }
}
.transition-box {
  transition: all 0.5s;
}
.isDivision {
  transform: rotateZ(180deg);
}
.icon {
  font-size: 18px;
}
.languageSelect {
  background: #f5f8fa;
  border: 1px solid #cbd6e2;
  border-radius: 4px;
  height: 32px;
  line-height: 32px;
  margin-left: 8px;
  text-align: center;
  width: 32px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}
.lang_setting {
  margin: 30px 42px;
}
.lang_setting_form {
  display: block;
  flex: 1;
}
::v-deep .el-form-item--small .el-form-item__label {
  position: relative;
  margin-top: 0;
}
::v-deep .el-form-item__content {
  flex: 1;
}
::v-deep .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
  position: absolute;
  left: -10px;
}
.language {
  display: inline-block;
  width: auto;
}
::v-deep input {
  width: 100% !important;
}
::v-deep .el-dialog__wrapper {
  z-index: 3000 !important;
}

::v-deep .is-required:before {
  position: absolute;
}

.flex-x {
  display: flex;
  align-items: center;
  white-space: nowrap;
}
</style>
